package com.fxz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fxz.entity.SysMenu;
import com.fxz.entity.SysRole;
import com.fxz.entity.SysUser;
import com.fxz.mapper.SysUserMapper;
import com.fxz.service.SysMenuService;
import com.fxz.service.SysRoleService;
import com.fxz.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fxz
 * @since 2021-05-04
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public SysUser getByUserName(String username) {
        return this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username));
    }

    /**
     * 获取角色信息和菜单权限信息
     * @param userId 用户id
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {

        String authority = "";

        SysUser user = sysUserMapper.selectById(userId);

        //如果redis中缓存这用户权限信息
        if(redisUtil.hasKey("GrantedAuthority:"+user.getUsername())){
            //从redis获取用户的权限信息
            authority = (String)redisUtil.get("GrantedAuthority:" + user.getUsername());
        }else{
            //根据用户id获取角色
            List<SysRole> roles = sysRoleService.list(
                    new LambdaQueryWrapper<SysRole>()
                            .inSql(SysRole::getId, "select role_id from sys_user_role where user_id = " + userId)
            );
            //将用户的角色用逗号连接起来 (角色要加ROLE_)
            if(!CollectionUtils.isEmpty(roles)){
                String roleCodes = roles.stream().map(item -> "ROLE_"+item.getCode()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }

            //根据用户id获取菜单id
            List<Long> menuIds = sysUserMapper.geNavMenuIds(userId);
            if(!CollectionUtils.isEmpty(menuIds)){
                List<SysMenu> menus = sysMenuService.listByIds(menuIds);
                String menuPerms = menus.stream().map(item -> item.getPerms()).collect(Collectors.joining(","));

                authority = authority.concat(menuPerms);
            }

            //将据用户角色信息和菜单权限信息缓存到redis
            redisUtil.set("GrantedAuthority:"+user.getUsername(),authority,60*60);
        }
        System.out.println("authority-->"+authority);
        return authority;
    }

    /**
     * 根据用户名清空用户权限缓存
     * @param username 用户名
     */
    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtil.del("GrantedAuthority:"+username);
    }

    /**
     * 角色id改变 清空用户权限缓存
     * @param roleId 角色id
     */
    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {

        List<SysUser> userList = this.list(
                new LambdaQueryWrapper<SysUser>()
                        .inSql(SysUser::getId, "select user_id from sys_user_role where role_id = " + roleId)
        );

        userList.forEach(item-> this.clearUserAuthorityInfo(item.getUsername()));
    }

    /**
     * 菜单id改变 清空用户权限信息
     * @param menuId 菜单id
     */
    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUser> sysUsers = sysUserMapper.listByMenuId(menuId);
    }
}
